import { getRoutes } from '@/api/menu';
import { constantRoutes } from '@/router';
import Layout from '@/layout/index';
import Lay from '@/lay/index';

function filterAsyncRouter(router, lastRouter = false, type = false) {
  return router.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = childrenRouter(route.children, route, type);
    } else {
      delete route['children'];
      delete route['redirect'];
    }
    return true;
  });
}

function childrenRouter(router, lastRouter = false, type = false) {
  return router.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Lay;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = childrenRouter(route.children, route, type);
    } else {
      delete route['children'];
      delete route['redirect'];
    }
    return true;
  });
}
const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve);
};

const state = {
  routes: [],
  addRoutes: [],
  sidebarRouters: [],
  defaultRoutes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  SET_SIDEBAR_ROUTERS: (state, routes) => {
    state.sidebarRouters = routes;
  },
  SET_DEFAULT_ROUTES: (state, routes) => {
    state.defaultRoutes = constantRoutes.concat(routes);
  },
};

const actions = {
  generateRoutes({
    commit }, info) {
    return new Promise(resolve => {
      getRoutes().then(res => {
        const sdata = JSON.parse(JSON.stringify(res.data.data));
        const rdata = JSON.parse(JSON.stringify(res.data.data));
        const sidebarRoutes = filterAsyncRouter(sdata);
        const rewriteRoutes = filterAsyncRouter(rdata, false, true);
        rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true });
        commit('SET_ROUTES', rewriteRoutes);
        commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes));
        commit('SET_DEFAULT_ROUTES', sidebarRoutes);
        resolve(rewriteRoutes);
      });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
